// index.js
Page({
  data: {
    historyList: []
  },

  onLoad(options) {
    this.loadHistory()
    
    // 处理分享链接
    if (options.shared === 'true' && options.videoUrl) {
      console.log('收到分享链接:', options.videoUrl)
      this.handleSharedVideo(options.videoUrl)
    }
  },

  // 处理分享的视频链接
  handleSharedVideo(videoUrl) {
    if (!videoUrl) return
    
    try {
      // 解码视频URL
      const decodedUrl = decodeURIComponent(videoUrl)
      console.log('解码后的视频URL:', decodedUrl)
      
      // 显示分享提示
      wx.showModal({
        title: '收到分享',
        content: '检测到分享的视频链接，是否要解析下载？',
        showCancel: true,
        cancelText: '取消',
        confirmText: '立即解析',
        success: (res) => {
          if (res.confirm) {
            // 根据URL判断平台并跳转
            this.navigateToPlatformByUrl(decodedUrl)
          }
        }
      })
    } catch (e) {
      console.error('处理分享链接失败:', e)
    }
  },

  // 根据URL判断平台并跳转
  navigateToPlatformByUrl(url) {
    let platform = ''
    
    if (url.includes('douyin.com') || url.includes('v.douyin.com')) {
      platform = 'douyin'
    } else if (url.includes('kuaishou.com') || url.includes('v.kuaishou.com')) {
      platform = 'kuaishou'
    } else if (url.includes('bilibili.com') || url.includes('b23.tv')) {
      platform = 'bilibili'
    } else if (url.includes('xiaohongshu.com') || url.includes('xhslink.com')) {
      platform = 'xiaohongshu'
    } else {
      wx.showToast({
        title: '无法识别视频平台',
        icon: 'none'
      })
      return
    }
    
    // 跳转到对应平台页面，并传递URL参数
    wx.navigateTo({
      url: `/pages/${platform}/${platform}?sharedUrl=${encodeURIComponent(url)}`
    })
  },

  // 跳转到对应平台页面
  navigateToPlatform(e) {
    const platform = e.currentTarget.dataset.platform
    console.log('选择平台:', platform)
    
    // 根据平台跳转到对应页面
    switch(platform) {
      case 'douyin':
        wx.navigateTo({
          url: '/pages/douyin/douyin'
        })
        break
      case 'kuaishou':
        wx.navigateTo({
          url: '/pages/kuaishou/kuaishou'
        })
        break
      case 'bilibili':
        wx.navigateTo({
          url: '/pages/bilibili/bilibili'
        })
        break
      case 'xiaohongshu':
        wx.navigateTo({
          url: '/pages/xiaohongshu/xiaohongshu'
        })
        break
      default:
        wx.showToast({
          title: '暂不支持该平台',
          icon: 'none'
        })
    }
  },


  // 加载历史记录
  loadHistory() {
    const historyList = wx.getStorageSync('downloadHistory') || []
    // 为已有的历史记录添加displayTitle字段
    const processedHistoryList = historyList.map(item => {
      if (!item.displayTitle) {
        const originalTitle = item.title || '未知标题'
        item.displayTitle = originalTitle.length > 10 ? originalTitle.substring(0, 10) + '...' : originalTitle
      }
      return item
    })
    this.setData({ historyList: processedHistoryList.slice(0, 5) })
  },

  // 点击历史记录项
  onHistoryItemTap(e) {
    const item = e.currentTarget.dataset.item
    // 兼容历史数据：如果没有 videoUrl 但有 url，则映射
    if (!item.videoUrl && item.url) {
      item.videoUrl = item.url
    }
    wx.navigateTo({
      url: `/pages/download/download?data=${encodeURIComponent(JSON.stringify(item))}`
    })
  },

  // 格式化时间
  formatTime(date) {
    const now = new Date()
    const diff = now - date
    const minutes = Math.floor(diff / 60000)
    const hours = Math.floor(diff / 3600000)
    const days = Math.floor(diff / 86400000)

    if (minutes < 1) return '刚刚'
    if (minutes < 60) return `${minutes}分钟前`
    if (hours < 24) return `${hours}小时前`
    if (days < 7) return `${days}天前`
    return date.toLocaleDateString()
  },

  // 格式化时长（从时间戳转换为可读格式）
  formatDuration(timestamp) {
    const date = new Date(timestamp * 1000)
    const now = new Date()
    const diff = now - date
    const minutes = Math.floor(diff / 60000)
    const hours = Math.floor(diff / 3600000)
    const days = Math.floor(diff / 86400000)

    if (minutes < 1) return '刚刚'
    if (minutes < 60) return `${minutes}分钟前`
    if (hours < 24) return `${hours}小时前`
    if (days < 7) return `${days}天前`
    return date.toLocaleDateString()
  },

  // 分享给好友
  onShareAppMessage() {
    return {
      title: '高效无损去水印工具',
      path: '/pages/index/index',
      imageUrl: '/images/share-icon.png'
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '高效无损去水印工具',
      path: '/pages/index/index',
      imageUrl: '/images/share-icon.png'
    }
  }

})
